/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2009, Around(J2)ME				                                 **
 **   All rights reserved.                                                   **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the New BSD License which accompanies this    			 **
 **   distribution.											                 **
 **   A copy is found in the textfile LICENSE.txt							 **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Main developers:                                                       **
 **     Juri Strumpflohner		http://blog.js-development.com	             **
 **		Matthias Braunhofer		http://matthias.jimdo.com                    **
 **                                                                          **
 **  **********************************************************************  */

package com.aroundj2me.model;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.HttpConnection;
/**
 * This class is responsible for doing the communication
 * with the outside world. It uses the HTTP protocol for
 * communicating with the Around(J2)ME server
 *
 */
public class Communicator extends AbstractHTTPCommunicator {
	private ProgressListener progListener;
	
	public Communicator(String url, ProgressListener progListener){
		this.progListener = progListener;
		this.progListener.initialize(4);
		this.connectionURL = url;
		this.statusMessage = "";
	}

	/**
	 * Thread run method
	 * The sending to the server is done inside here. After successfully finishing
	 * the work, all listeners are notifyed
	 */
	public void run() {
		this.statusMessage = "";
		
		HttpConnection hc = null;
		InputStream in = null;
		OutputStream out = null;
		if(progListener!=null) progListener.incrementProgress();
		try{
			hc = createConnection(HttpConnection.POST);
//			hc.setRequestProperty("User-Agent",	System.getProperty("microedition.profiles"));
			hc.setRequestProperty("Content-Type", "application/xml; charset=iso-8859-1");
			hc.setRequestProperty("Content-Length", Integer.toString(request.length()));
			
			out = hc.openOutputStream();
			out.write(request.getBytes());
			out.close();
			out = null;
			
			if(progListener!=null) progListener.incrementProgress();
			
			if(hc.getResponseCode() == HttpConnection.HTTP_OK){
				in = hc.openInputStream();
				
				byte[] data = null;
				int length = (int)hc.getLength();
				if (length > 0) {
	                int bytesread = 0;
	                data = new byte[length];
	                for (int offset = 0; offset < length;
	                     offset += bytesread) {
	                     bytesread = in.read(data, offset, length-bytesread);
	                }
				}
				
				if(progListener!=null) progListener.incrementProgress();
				
				response = new String(data);
			}else{
				response = null;
				statusMessage = "The connection with the server failed! Please retry again.";
			}
		}catch (SecurityException e) {
			statusMessage = "The process has been aborted by the user!";
		}catch (Exception e) {
			statusMessage = "The connection with the server failed! Please retry again.";
		}finally{
			try{
				if(in != null) in.close();
				if(out != null) out.close();
				if(hc != null) hc.close();
			}catch(IOException ioe){}
			if(progListener!=null) progListener.incrementProgress();
			notifyListener();
		}
	}
	
}
